from qcloudsms_py.httpclient import HTTPError

from .settings import *
from utils.log import get_logger
from qcloudsms_py import SmsSingleSender
# 获取验证码的函数

logger = get_logger()

import random
def get_code():
    code_str = ''
    for i in range(4):
        number = str(random.randint(0,9))
        code_str += number
    return code_str

# 可右击运行测试一下验证码
# if __name__ == '__main__':
#     print(get_code())

# 发送短信的函数
def send_sms(phone, code):
    ssender = SmsSingleSender(APPPID, APPKEY)
    params = [code]  # 当模板没有参数时，`params = []`
    try:
        result = ssender.send_with_param(86, phone,
                                         TEMPLATE_ID, params, sign=SMS_SIGN, extend="", ext="")
        if result['result'] == 0:
            # 记录日志
            return True
        else:
            logger.warning('%s手机号，发送短信失败,失败原因是%s' % (phone, result['errmsg']))
            return False
    except Exception as e:
      print(e)
    # result = ssender.send_with_param(86, phone,
    #                                  TEMPLATE_ID, params, sign=SMS_SIGN, extend="", ext="")
    # print(result)


